<template>
  <div style="width: 70%; margin: 10px auto;">
    <div style="padding: 20px; border: 1px solid #ddd; border-radius: 5px">
      <div style="display: flex; align-items: center; grid-gap: 20px">
        <div style="font-size: 20px">宠物用品列表({{ data.totalGoodsNumber }}个)</div>
        <div style="flex: 1">
          <el-select style="width: 100%" v-model="data.addressId">
            <el-option v-for="address in data.addressList" :key="address.id" :value="address.id" :label="address.name + ' - ' + address.address + ' - ' + address.phone"></el-option>
          </el-select>
        </div>
        <div style="width: 260px; display: flex; align-items: center; justify-content: flex-end">
          <span style="font-size: 17px;">已选总价格</span>
          <span style="font-size: 20px; font-weight: bold; color: red; margin-left: 5px; display: inline-block; width: 100px; display: inline-block; width: 100px">
            ￥{{ data.money }}
          </span>
          <el-button type="danger" style="margin-left: 10px; border-radius: 20px" @click="submitOrder">下单</el-button>
        </div>
      </div>
      <div style="margin-top: 30px">
        <el-table tooltip-effect="dark" stripe :data="data.cartList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"/>
          <el-table-column prop="goodsName" label="宠物用品名称"></el-table-column>
          <el-table-column prop="goodsImage" label="宠物用品图片">
            <template #default="scope">
              <el-image style="width: 80px; height: 80px; border-radius: 5px" :src="scope.row.goodsImage" :preview-src-list="[scope.row.goodsImage]" preview-teleported></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="goodsPrice" label="宠物用品单价">
            <template #default="scope">
              <span style="color: red; font-size: 20px"> ￥{{ scope.row.goodsPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="shopName" label="宠物店名称">
            <template #default="scope">
              <div style="cursor: pointer" @click="router.push('/front/petShopDetail?id=' +  scope.row.shopId)">{{ scope.row.shopName }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="num" label="宠物用品数量">
            <template #default="scope">
              <div style="display: flex; justify-items: center; align-items: center;">
                <el-button type="danger" size="small" style="margin-right: 10px; border-radius: 20px" @click="subGoodsNumber(scope.row.id)">减少</el-button>
                <div style="font-size: 15px">{{ scope.row.num }}</div>
                <el-button type="info" size="small" style="margin-left: 10px; border-radius: 20px" @click="addGoodsNumber(scope.row.id)">增加</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" fixed="right">
            <template #default="scope">
              <el-button type="danger" plain @click="deleteGoods(scope.row.id)">移出购物车</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script setup>
  import {reactive} from 'vue'
  import request from '@/utils/request.js'
  import { ElMessage } from 'element-plus'
  import router from "@/router/index.js"

  const data = reactive({
    user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
    cartList: [],
    addressList: [],
    totalGoodsNumber: 0,
    addressId: null,
    money: 0,
    selectedIdList: null,
  })

  // 询当前用户的收货地址
  const loadAddress = () => {
    request.get('/address/query/all', {
      params: {
        userId: data.user.id
      }
    }).then(res => {
      if (res.code === '200') {
        data.addressList = res.data
        data.addressId = res.data.length ? res.data[0].id : null
      } else {
        ElMessage.error(res.msg)
      }
    })
  }
  loadAddress()

  // 查询当前用户的购物车
  const loadCart = () => {
    request.get('/cart/query').then(res => {
      if (res.code === '200') {
        data.cartList = res.data
      } else {
        ElMessage.error(res.msg)
      }
    })
  }
  loadCart()

  const handleSelectionChange = (rows) => {
    data.totalGoodsNumber = 0
    rows.forEach(item => {
      data.totalGoodsNumber += item.num
    })
    data.selectedIdList = rows.map(row => row.id)
    data.money = 0
    rows.forEach(row => {
      data.money += row.goodsPrice * row.num
    })
    data.money = data.money.toFixed(2)
  }

  // 在购物车减少宠物用品数量
  const subGoodsNumber = (id) => {
    request.put('/cart/update/number/sub?id=' + id).then(res => {
        if(res.code === '200') {
          ElMessage.success('减少成功')
        } else {
          ElMessage.error(res.msg)
        }
        loadCart()
    })
  }

  // 在购物车增加宠物用品数量
  const addGoodsNumber = (id) => {
    request.put('/cart/update/number/add?id=' + id).then(res => {
      if(res.code === '200') {
        ElMessage.success('增加成功')
      } else {
        ElMessage.error(res.msg)
      }
      loadCart()
    })
  }

  // 将一种宠物用品移出购物车
  const deleteGoods = (id) => {
    request.delete('/cart/delete/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('移出购物车成功')
        loadCart()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  // 下单
  const submitOrder = () => {
    // 1.检查是否选中商品
    if (!data.selectedIdList || data.selectedIdList.length === 0) {
      ElMessage.error('请选择要购买的商品')
      return
    }
    // 2.检查是否存在可用地址
    if (data.addressList.length === 0) {
      ElMessage.error('请先添加收货地址')
      return
    }
    // 3.检查是否已选择地址
    if (!data.addressId) {
      ElMessage.error('请选择收货地址')
      return
    }
    // 4.构造请求数据
    const dtoList = data.cartList
        .filter(cart => data.selectedIdList.includes(cart.id)) // 过滤出选中的商品
        .map(cart => ({
          cartId: cart.id,          // 购物车ID
          goodsId: cart.goodsId,    // 商品ID（从购物车项获取）
          shopId: cart.shopId,      // 店铺ID（从购物车项获取）
          addressId: data.addressId, // 用户选择的地址ID
          goodsNumber: cart.num     // 商品数量（从购物车项获取）
        }));
    // 5.向后端接口发送请求
    request.post('/goodsOrders/add', dtoList).then(res => {
      if (res.code === '200') {
        ElMessage.success('下单成功')
        loadCart()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

</script>